package com.nisco.dms.util.auto;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 
 * @author Robin
 * @version 1.0.0
 */
public class TextFile extends ArrayList<String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Read a file as a single string:
	 * 
	 * @param fileName
	 * @return
	 */
	public static String read(String fileName) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader in = new BufferedReader(new FileReader(new File(
					fileName).getAbsoluteFile()));
			try {
				String s;
				while ((s = in.readLine()) != null) {
					sb.append(s);
					sb.append("\n");
				}
			} finally {
				in.close();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return sb.toString();
	}

	/**
	 * Write a single file in one method call:
	 * 
	 * @param fileName
	 * @param text
	 */
	public static void write(String fileName, String text) {
		try {
			PrintWriter out = new PrintWriter(
					new File(fileName).getAbsoluteFile());
			try {
				out.print(text);
			} finally {
				out.close();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * Read a file,split by any regular expression:
	 * 
	 * @param fileName
	 * @param splitter
	 */
	public TextFile(String fileName, String splitter) {
		super(Arrays.asList(read(fileName).split(splitter)));
		// Regular expression splite() often leaves an empty String at the first
		// postion:
		if (get(0).equals(""))
			remove(0);
	}

	/**
	 * Normally read by lines:
	 * 
	 * @param fileName
	 */
	public TextFile(String fileName) {
		this(fileName, "\n");
	}

	/**
	 * 
	 * @param fileName
	 */
	public void write(String fileName, List<String> list) {
		try {
			PrintWriter out = new PrintWriter(
					new File(fileName).getAbsoluteFile());
			try {

				for (String item : this) {
					for (int i = 0; i < list.size(); i++) {
						if (item.contains(list.get(i).split("<==>")[0]
								.toString())) {
							item = item.replace(
									list.get(i).split("<==>")[0].toString(),
									list.get(i).split("<==>")[1].toString());
						}
					}
					out.println(item);
				}

			} finally {
				out.close();
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	// public static void main(String[] args){
	// // String file = read("D:\\TextFile.java");
	// // write("D:\\aa.txt", file);
	// TextFile textFile = new
	// TextFile("src/main/resources/codeTemplate/TextFile.java");
	// textFile.write("D:\\aa2.txt");
	// }
}
